$(document).ready(function () {
  var btnR = document.getElementById("btnR");
  var btnD = document.getElementById("btnD");
  var btnL = document.getElementById("btnL");
  var btnU = document.getElementById("btnU");
  var btnStop = document.getElementById("btnStop");
  var snake = document.getElementById("snake");
  var top = 195;
  var left = 295;
  var candyLeft;
  var candyTop;
  //控制方向的定时器
  var Uid = null;
  var Did = null;
  var Lid = null;
  var Rid = null;
  var Allid =null;
  var resCandy;

  //存储糖果
  var candyList = [
    "#icon-Candy1",
    "#icon-tangguo-",
    "#icon-tangguo",
    "#icon-lingshi_tangguo",
    "#icon-tangguo1",
    "#icon-tangguo2",
    "#icon-ziyuan",
    "#icon-shengdanjie-tangguo",
    "#icon-tangguo3",
    "#icon-tangguo4",
  ];
  //页面初始化
  ranCandyAndPosition();

  Allid = setInterval(function () {
    //触碰糖果判断
    if (Math.abs(top - candyTop) < 20 && Math.abs(left - candyLeft) < 20) {
      ranCandyAndPosition();
      //吃到糖果后 身体增加长度
      var color = Math.random().toString(16).substring(2, 8);
      $(".screen").append(
        `<div class='sn' style="background-color:#${color}"></div>`
      );
    }
 
    //边界判断
    if (
      snake.offsetTop < 0 ||
      snake.offsetTop > 380 ||
      snake.offsetLeft > 580 ||
      snake.offsetLeft < 0
    ) {
      gameOver();
    }
  }, 1);
   //上一个按下的方向
   var lastDir = 0;
   // 37 38 39 40 左上右下
   $(window).keydown(function (event) {
     // console.log(event.keyCode);
     switch (event.keyCode) {
       case 37:
         //如果按下的建和上一个按键一样不执行，
         //如果正在向右移动不能向左移动（防止蛇穿过身体）
         if (lastDir !== 39 && lastDir !== 37) {
           lastDir = 37;
           //先停止所有方向的移动
           stopAll();
           //再移动
           Lid = setInterval(move, 100, event.keyCode);
         }
         break;
       case 38:
         if (lastDir !== 40 && lastDir !== 38) {
           lastDir = 38;
           stopAll();
           Uid = setInterval(move, 100, event.keyCode);
         }
         break;
       case 39:
         if (lastDir !== 37 && lastDir !== 39) {
           lastDir = 39;
           stopAll();
           Rid = setInterval(move, 100, event.keyCode);
         }
         break;
       case 40:
         if (lastDir !== 38 && lastDir !== 40) {
           lastDir = 40;
           stopAll();
           Did = setInterval(move, 100, event.keyCode);
         }
 
         break;
     }
   });
   

  //封装随机生成食物坐标和食物图标的方法
  function ranCandyAndPosition() {
    candyLeft = Math.floor(Math.random() * 561) + 10;
    candyTop = Math.floor(Math.random() * 361) + 10;
    //随机获取存在数组里面的图标名称
    resCandy = candyList[Math.floor(Math.random() * candyList.length)];
    console.log("随机出的食物" + resCandy);
    //随机出的食物坐标和图标渲染到页面
    $("svg")
      .css({ left: candyLeft + "px", top: candyTop + "px" })
      .children("use")
      .attr({ "xlink:href": resCandy });
    //
  }
  function gameOver() {
    top = 195;
    left = 295;
    stopAll();
    //清除长度
    $("#snake").siblings("div[class='sn']").remove();
    ranCandyAndPosition();
    alert("游戏结束");
    snake.style.top = top + "px";
    snake.style.left = left + "px";
   


  }
  function tolong() {
    //遍历蛇的身体
    for (var i = $("main>div").length - 1; i > 0; i--) {
      if (
        left == parseInt($(`main>div:eq(${i})`).css("left")) &&
        top == parseInt($(`main>div:eq(${i})`).css("top"))
      ) {
        gameOver();
      }



      /*  将最后一个盒子的x y 坐标改为 倒数第二的 
      倒数第二改成倒数第三的x y
      以此类推
      */
      $("main>div:eq(" + i + ")").css({
        // parseInt  将字符串转数字  遇到第一个非数字的就停下
        left: parseInt($(`main>div:eq(${i - 1})`).css("left")),
        top: parseInt($(`main>div:eq(${i - 1})`).css("top")),
      });
    }
  }
  //给蛇的上下左右坐标添加偏移量
  function move(code) {
    switch (code) {
      case 38:
        tolong();
        top -= 20;
        snake.style.top = top + "px";
        break;
      case 40:
        tolong();
        top += 20;
        snake.style.top = top + "px";
        break;
      case 39:
        tolong();
        left += 20;
        snake.style.left = left + "px";
        break;
      case 37:
        tolong();
        left -= 20;

        snake.style.left = left + "px";
        break;
    }
  }
  //清除上下左右移动的定时器
  function stopAll() {
    clearInterval(Lid);
    clearInterval(Rid);
    clearInterval(Did);
    clearInterval(Uid);
  }
 
  btnStop.onclick = function () {
    //停止所有方向定时器--停止所有方向的移动
    stopAll();
  };
  btnR.onclick = function () {
    if (lastDir !== 37 && lastDir !== 39) {
      lastDir = 39;
      stopAll();
      Rid = setInterval(move, 100, 39);
    }
  };
  btnD.onclick = function () {
    if (lastDir !== 38 && lastDir !== 40) {
      lastDir = 40;
      stopAll();
      Did = setInterval(move, 100, 40);
    }
  };
  btnU.onclick = function () {
    if (lastDir !== 40 && lastDir !== 38) {
      lastDir = 38;
      stopAll();
      Uid = setInterval(move, 100, 38);
    }
  };
  btnL.onclick = function () {
    if (lastDir !== 39 && lastDir !== 37) {
      lastDir = 37;
      //先停止所有方向的移动
      stopAll();
      //再移动
      Lid = setInterval(move, 100, 37);
    }
  };




 

});
